<!-- 组织信息模板 -->
<template>
  <ContentCard>
    <template #header>
      <PageHeaderNew :title="title" :isShowBtn="true" show-back>
      </PageHeaderNew>
    </template>
    <ConditionBox :margin-bottom="20">
      <template #left>
        <a-input-search
          :style="{ width: '320px' }"
          placeholder="请输入模板名称"
          search-button
          v-model="nameSearch"
          @press-enter="onSearch"
          @search="onSearch"
        >
          <template #button-icon>
            <icon-search />
          </template>
        </a-input-search>
      </template>
      <template #right>
        <a-button type="primary" @click="add">新增模板</a-button>
        <a-button type="outline" @click="del(null)" status="danger"
          >批量删除</a-button
        >
      </template>
    </ConditionBox>
    <TableTurn ref="tableRef" :tableData="templateData" :args="args">
      <a-table-column align="center" :width="80">
        <template #title> 序号 </template>
        <template #cell="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
      </a-table-column>
      <a-table-column
        align="center"
        :width="150"
        title="组织模板名称"
        dataIndex="name"
      >
      </a-table-column>
      <a-table-column
        align="center"
        :width="150"
        title="组织节点"
        dataIndex="node"
      >
        <template #cell="{ record }">
          {{ record.node === 1 ? '公司' : record.node === 2 ? '部门' : '门店' }}
        </template>
      </a-table-column>
      <a-table-column
        align="center"
        :width="300"
        title="描述"
        dataIndex="remark"
      >
      </a-table-column>
      <a-table-column
        align="center"
        :width="150"
        title="启用状态"
        dataIndex="enable"
      >
        <template #cell="{ record }">
          <a-tag
            class="enable"
            :color="
              record.enable === 1
                ? `rgb(var(--green-1))`
                : 'rgb(var(--danger-1))'
            "
            :style="{
              color:
                record.enable === 1
                  ? `rgb(var(--green-6))`
                  : 'rgb(var(--danger-6))',
              '--enable':
                record.enable === 1
                  ? `rgb(var(--green-6))`
                  : 'rgb(var(--danger-6))'
            }"
          >
            {{ record.enable === 1 ? '启用' : '停用' }}
          </a-tag>
        </template>
      </a-table-column>
      <a-table-column align="center" title="操作" :width="100" fixed="right">
        <template #cell="{ record }">
          <a-space :size="0">
            <a-tooltip content="预览">
              <icon-eye
                size="20"
                @click="goPreview(record.id)"
                style="color: #5085ff; cursor: pointer"
              />
            </a-tooltip>
            <a-tooltip content="复制">
              <IconFont
                type="icon-fuzhi"
                :size="26"
                :style="{
                  cursor: 'pointer'
                }"
                @click="goCopy(record.id)"
              />
            </a-tooltip>
            <a-tooltip content="编辑">
              <IconFont
                type="icon-edit"
                :size="26"
                :style="{
                  cursor: 'pointer'
                }"
                @click="goEdit(record.id)"
              />
            </a-tooltip>
            <a-tooltip content="删除" position="left">
              <a-popconfirm content="是否确认删除该条数据?" @ok="del(record)">
                <IconFont
                  type="icon-delete"
                  :size="26"
                  :style="{
                    cursor: 'pointer'
                  }"
                />
              </a-popconfirm> </a-tooltip
          ></a-space>
        </template>
      </a-table-column>
    </TableTurn>
  </ContentCard>
  <CopyModal
    v-model:visible="copyVisible"
    @copy-emit="copyEmit"
    @copyEditEmit="copyEditEmit"
    :validateFun="validateName"
  />
  <NoticeTemplate
    ref="templateRef"
    :data="currRecord.data"
    :business-type="businessType"
    :add="addData"
    :validateFun="validateName"
    :tab-code-list="businessType"
    :edit="EditData"
    :fn="tableRef"
    :title="`组织信息模板`"
    sliceName="组织"
    :isOrganizationNode="true"
  ></NoticeTemplate>
  <PreviewForm
    :data="currRecord.data"
    v-model:visible="previewFormVisible"
    sliceName="组织"
  >
  </PreviewForm>
</template>

<script lang="ts" setup>
import {
  GetDepartmentTemplate,
  PutOrganizationTemplateState,
  DelOrganizaitonTemplate,
  PostOrganizaitonTemplate,
  PutOrganizaitonTemplate,
  GetDepartmentTemplateDetail,
  CheckDepartmentTemplate,
  DelOrganizationTemplateCollections,
  DelOrganizationTemplateControls
} from '@/apis/management/organization/baseSetting/organizationalType/index';
import { validateRules } from '@/utils/common';
// import { GetControl } from '@/apis/management/base';
import { useSetupFormStore } from '@/store';
import { Message, Modal } from '@arco-design/web-vue';
import { cloneDeep } from 'lodash';

const name = useRoute().query.name; // 组织类型名字
const title = `组织信息模板库`;
const store = useSetupFormStore();
let tableRef = ref();
let templateRef = ref();

const businessType = ref([
  'SER_FUNC85B7C3790D804083B2B848E22935E5CE',
  'baseComponent'
]);
// 具体要展示哪种业务控件
const tabCodeList = [
  'allComponent',
  'baseComponent',
  'businessComponent',
  'organizationComponent'
];

// 表格配置
const args = reactive({
  rowSelection: {
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false
  }
});
/* 储存选择的数据 */
const selectedList = computed(() => tableRef.value.selectedList);
const selectedListData = computed(() => tableRef.value.selectedListData);
// 储存当前数据
const currRecord: any = reactive({
  data: {}
});
let currId = ref(0);

let nameSearch = ref(''); //名称搜索框
let originData = ref(); // 储存原始数据
// 获取列表信息
const templateData = async (pageData?: any) => {
  const res: any = await GetDepartmentTemplate({
    ...pageData,
    name: nameSearch.value,
    ownerType: 3
  });

  originData.value = cloneDeep(res?.content);
  return Promise.resolve(res);
};

// 点击新增模板按钮
const add = () => {
  currRecord.data = {
    name: '',
    enable: 1,
    remark: ''
  };
  templateRef.value.fullScreen();
};

let previewFormVisible = ref(false);

// 模板查重函数
const validateName = async (name: string) => {
  try {
    if (name === currRecord.data.name && currRecord.data.id) {
      //
    } else {
      const data = {
        ownerType: 3, // 组织模板库写死3
        name
      };
      const res = await validateRules(CheckDepartmentTemplate, data);
      return Promise.resolve(res);
    }
  } catch (error: unknown) {
    console.log(error);
  }
};

// 预览
const goPreview = async (id: number) => {
  try {
    const res: any = await GetDepartmentTemplateDetail({ id });
    currRecord.data.name = res.name;
    currRecord.data.details = res.collectionModel;
    previewFormVisible.value = true;
  } catch (error: unknown) {
    console.log(error);
  }
};

// 编辑 初始化控件数据
const goEdit = async (id: number, name?: string) => {
  const record: any = cloneDeep(await GetDepartmentTemplateDetail({ id }));
  record.seconds = record.collectionModel;
  delete record.collectionModel;
  if (name) {
    record.name = name;
    delete record.id;
  }
  record.seconds.forEach((ele: any) => {
    if (name) delete ele.id;
    ele.componentList = ele.controlModel;
    delete ele.componentModel;
    ele.componentList.forEach((item: any) => {
      const { ctlCnName, ctlEnName, ctlComponentType, ctlCode, ctlFieldName } =
        item;
      item.uuid = ctlCode;
      item.componentName = ctlCnName;
      item.componentType = ctlComponentType;
      item.code = ctlCode;
      item.fieldName = ctlFieldName;
      item.enName = ctlEnName;
      if (name) delete item.id;
    });
  });
  currRecord.data = cloneDeep(record);
  templateRef.value.fullScreen();
};
// 新增 模板新增函数
const addData = async (data: any, componentList: any) => {
  try {
    // 第一层，返回templateId赋值给第二层子集
    const templateId = await PostOrganizaitonTemplate({
      level: 1, // 默认传1
      template: {
        enable: data.enable,
        name: data.name,
        remark: data.remark,
        node: data.node,
        ownerType: 3 // 组织模板库默认传3
      },
      funcTemplateType: 4 // 组织默认传4
    });
    let component = cloneDeep(componentList);
    // 用createdAt进行判断用户是否是复制再编辑模板
    if (component[0]?.createdAt) {
      component = [
        {
          componentList: component
        }
      ];
    }
    for (let [index, item] of component.entries()) {
      for (let item2 of item.componentList) {
        const collection = {
          cnName: item2.cnName,
          enName: item2.enName,
          subCode: item2.subCode,
          orderNo: item2.sort || index,
          templateId
        };
        const collectionId = await PostOrganizaitonTemplate({
          level: 2, // 第二层默认传2
          collection
        });
        // 将返回的collectionId赋值给每一个控件
        const control = item2.componentList.map((item2: any) => {
          item2.collectionId = collectionId;
          let data;
          if (item2.subsetControlRel) {
            data = {
              ...item2,
              ...item2.subsetControlRel
            };
          } else {
            data = {
              ...item2
            };
          }
          if (data.subsetControlRel) delete data.subsetControlRel;

          return data;
        });
        await PostOrganizaitonTemplate({
          level: 3, // 第三层传3
          control
        });
      }
    }
    currRecord.data = {
      name: '',
      enable: 1,
      remark: ''
    };
    tableRef.value.loadData();
  } catch (error: unknown) {
    console.log(error);
  }
};
// 新增 模板编辑函数
const EditData = async (data: any, componentList: any) => {
  try {
    console.log('====================================123123');
    console.log(data);
    console.log(componentList);
    console.log('====================================');
    const templateId = data.id;
    // 第一层，返回templateId赋值给第二层子集
    await PutOrganizaitonTemplate({
      level: 1, // 默认传1
      template: {
        ...data,
        ownerType: 3 // 组织默认传1
      },
      funcTemplateType: 4 // 组织默认传4
    });

    // 删除子集
    if (store.getCollectionsIds.length > 0) {
      await DelOrganizationTemplateCollections({
        ids: store.getCollectionsIds
      });
      store.delCollectionsIds = [];
    }

    // 删除控件
    if (store.getControlIds.length > 0) {
      await DelOrganizationTemplateControls({
        ids: store.getControlIds
      });
      store.delControlIds = [];
    }

    const component = cloneDeep(componentList);
    // // 循环修改值的结构
    for (let [index, item] of component.entries()) {
      const collection: any = {
        cnName: item.cnName,
        enName: item.enName,
        subCode: item.subCode,
        orderNo: item.sort || index,
        templateId
        // pid: item2.pid || 0
      };
      let collectionId = 0;
      if (item.id) {
        collection.id = item.id;
        await PutOrganizaitonTemplate({
          level: 2, // 第二层默认传2
          funcTemplateType: 1, // 组织默认传1
          collection
        });
        collectionId = item.id;
      } else {
        collectionId = (await PostOrganizaitonTemplate({
          level: 2, // 第二层默认传2
          collection
        })) as number;
      }
      for (let item2 of item.componentList) {
        item2.collectionId = collectionId;
      }
      await PutOrganizaitonTemplate({
        level: 3, // 第三层传3
        funcTemplateType: 1, // 组织默认传1
        control: item.componentList
      });
    }

    currRecord.data = {
      name: '',
      enable: 1,
      remark: ''
    };
    tableRef.value.loadData();
  } catch (error: unknown) {
    console.log(error);
  }
};

let copyVisible = ref(false);
// 显示复制弹窗
const goCopy = (id: number) => {
  currId.value = id;
  copyVisible.value = true;
};

//  直接复制
const copyEmit = async (formData: any) => {
  try {
    const record: any = await GetDepartmentTemplateDetail({ id: currId.value });
    delete record.id;
    delete record.createdAt;
    record.required = 2;
    record.name = formData.name;
    const template = cloneDeep(record);
    delete template.collectionModel;
    const templateId = await PostOrganizaitonTemplate({
      level: 1, // 默认传1
      template: {
        ...template,
        ownerType: 3, // 组织模板库默认传3
        isShowDefault: 2 // 复制的时候默认为不是默认模板
      },
      funcTemplateType: 4 // 组织默认传4
    });
    const component = cloneDeep(record.collectionModel);
    for (let [index, item] of component.entries()) {
      delete item.id;
      const collection = {
        cnName: item.cnName,
        enName: item.enName,
        subCode: item.subCode,
        orderNo: item.sort || index,
        templateId
      };
      const collectionId = await PostOrganizaitonTemplate({
        level: 2, // 第二层默认传2
        collection
      });
      // 将返回的collectionId赋值给每一个控件
      item.controlModel.forEach((item2: any, index3: number) => {
        item2.collectionId = collectionId;
        delete item2.id;
      });
      await PostOrganizaitonTemplate({
        level: 3, // 第三层传3
        control: item.controlModel
      });
    }
    currRecord.data = {
      name: '',
      enable: 1,
      remark: ''
    };
    tableRef.value.loadData();
  } catch (error) {
    console.log(error);
  }
};

// 复制弹窗点击确认并编辑
const copyEditEmit = (formData: any) => {
  goEdit(currId.value, formData.name);
};

// 修改模板默认状态
const stateChange = async (record: any) => {
  try {
    // 获取更改状态之前的模板数据，并判断状态是否和当前的一样，如果一样则不能改成默认模板
    const temp = originData.value.find((item: any) => item.id === record.id);
    if (temp.isShowDefault === 1) Message.error('必须拥有一个默认模板！');
    else if (temp.enable !== 1)
      Message.error('不能将未启用的模板当作默认模板!');
    else
      await PutOrganizationTemplateState({
        ownerType: 1,
        id: record.id
      });
    tableRef.value.loadData();
  } catch (error: unknown) {
    console.log(error);
  }
};

// 删除数据
const del = async (record: any) => {
  try {
    if (!record) {
      if (selectedList.value.length === 0) {
        Message.error('请至少选择一项！');
      } else {
        Modal.confirm({
          title: '提示',
          content: '确定要删除选中的数据吗？',
          onOk: async () => {
            try {
              if (
                selectedListData.value.find(
                  (item: any) => item.isShowDefault === 1
                )
              ) {
                Message.error('默认模板不能删除！');
              } else {
                await DelOrganizaitonTemplate({
                  ids: selectedList.value
                });
                tableRef.value.selectedList = [];
                tableRef.value.loadData();
              }
            } catch (error: unknown) {
              console.log(error);
            }
          }
        });
      }
    } else {
      if (record.isShowDefault === 1) Message.error('默认模板不能删除！');
      else {
        await DelOrganizaitonTemplate({
          ids: [record.id]
        });
        tableRef.value.selectedList = [];
        tableRef.value.loadData();
      }
    }
  } catch (error: unknown) {
    console.log(error);
  }
};

// 搜索框
const onSearch = () => {
  tableRef.value.loadData({
    pageNumber: 0,
    pageSize: -1
  });
};
</script>

<style scoped lang="less">
.contain {
  padding: 10px 20px;
  .header {
    display: flex;
    justify-content: space-between;
    &-front {
      position: relative;
      line-height: 30px;
    }
    margin-bottom: 20px;
  }
  .top {
    display: flex;
    justify-content: space-between;
    margin-bottom: 15px;
    .input {
      width: 320px;
    }
  }
}
.enable::before {
  content: '';
  display: inline-block;
  width: 5px;
  height: 5px;
  border-radius: 50%;
  position: relative;
  right: 3px;
  background-color: var(--enable);
}
</style>
